//
//  CustormSliderView.m
//  17LoanTemplate
//
//  Created by gynjobs on 2017/8/25.
//  Copyright © 2017年 cangming. All rights reserved.
//

#import "CustormSliderView.h"

#define SLIDER_W     self.bounds.size.height
#define SLIDER_H     self.bounds.size.height
#define SLIDER_BG_H  8


@interface CustormSliderView () <UIGestureRecognizerDelegate>

@property (nonatomic,strong) UIView *bgView;
@property(assign,nonatomic)BOOL initLayout;;

@end

@implementation CustormSliderView

- (instancetype)init {
    if (self = [super init]) {
        [self initSubViews];
    }
    
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self initSubViews];
}

+ (instancetype)sliderWithMax:(NSInteger)max andMin:(NSInteger)min andPrecise:(NSInteger)precise {
    CustormSliderView *sliderView = [[CustormSliderView alloc] init];
    sliderView.dataMax = max;
    sliderView.dataMin = min;
    sliderView.dataPrecise = precise;
    
    return sliderView;
}

- (CAGradientLayer *)gradientLayer {
    if (!_gradientLayer) {
        _gradientLayer = [CAGradientLayer layer];
        _gradientLayer.frame = CGRectMake(0, 0, 0, SLIDER_BG_H);
        _gradientLayer.startPoint = CGPointMake(0, 1);
        _gradientLayer.endPoint = CGPointMake(1, 1);
        _gradientLayer.colors = @[(__bridge id)[UIColor colorWithString:@"#ffb845"].CGColor,
                                  (__bridge id)[UIColor colorWithString:@"#ffb845"].CGColor];
    }
    
    return _gradientLayer;
}

- (void)setSliderViewCornerRadius:(CGFloat)sliderViewCornerRadius{
    _sliderViewCornerRadius = sliderViewCornerRadius;
    self.layer.cornerRadius = sliderViewCornerRadius;
    
    self.gradientLayer.cornerRadius = sliderViewCornerRadius;
    self.bgView.layer.cornerRadius = sliderViewCornerRadius;
}

- (void)setInitAmount:(NSInteger)initAmount{
    _initAmount = initAmount;
    if (initAmount == 0) {
        return;
    }
    
    CGFloat maxW = self.slider.superview.frame.size.width - SLIDER_W;
    CGFloat uiPrecise = maxW * self.dataPrecise / (self.dataMax - self.dataMin) ;
    self.slider.frame = CGRectMake((self.initAmount - self.dataMin) / self.dataPrecise * uiPrecise, 0, SLIDER_W, SLIDER_H);
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    self.bgView.frame = CGRectMake(0, (self.bounds.size.height - SLIDER_BG_H) / 2, self.bounds.size.width, SLIDER_BG_H);
    self.slider.layer.cornerRadius = SLIDER_W / 2;
    self.bgView.layer.cornerRadius = self.gradientLayer.cornerRadius;
    
    if (!self.initLayout) {
        if (self.initAmount == 0) {
            self.slider.frame = CGRectMake(0, 0, SLIDER_W, SLIDER_H);
        }else{
            CGFloat maxW = self.slider.superview.frame.size.width - SLIDER_W;
            CGFloat uiPrecise = maxW * self.dataPrecise / (self.dataMax - self.dataMin) ;
            self.slider.frame = CGRectMake((self.initAmount - self.dataMin) / self.dataPrecise * uiPrecise, 0, SLIDER_W, SLIDER_H);
        }
        self.slider.image = [UIImage imageNamed:@"money_point_img.png"];
        
        self.initLayout = YES;
    }
}

- (void)dealloc {
    [self.slider removeObserver:self forKeyPath:@"frame"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if (change && change[@"new"]) {
        NSValue *data = change[@"new"];
        CGRect rect = [data CGRectValue];
        
        CGFloat centerX = rect.origin.x + rect.size.width / 2;
        
        [CATransaction begin];
        [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
        
        self.gradientLayer.frame = CGRectMake(0, 0, centerX, self.bgView.frame.size.height);
        [CATransaction commit];
    }
}

- (void)initSubViews{
    self.backgroundColor = [UIColor clearColor];
    
    self.bgView = [UIView new];
    [self addSubview:self.bgView];
    self.bgView.backgroundColor = [UIColor colorWithString:@"ebebeb"];
    
    self.slider = [UIImageView new];
    self.slider.userInteractionEnabled = YES;
    self.slider.backgroundColor = [UIColor clearColor];
    [self addSubview:_slider];
    
    self.slider.layer.masksToBounds = YES;
    [self.bgView.layer insertSublayer:self.gradientLayer atIndex:0];
    
    [self.slider addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
    
    UIPanGestureRecognizer *panGest = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
    panGest.delegate = self;
    [self.slider addGestureRecognizer:panGest];
}

- (void)panAction:(UIPanGestureRecognizer *)gestureRecognizer {
    CGPoint currentPoint = [gestureRecognizer translationInView:gestureRecognizer.view.superview];
    
    gestureRecognizer.view.frame = CGRectMake(gestureRecognizer.view.frame.origin.x + currentPoint.x, gestureRecognizer.view.frame.origin.y,gestureRecognizer.view.frame.size.width,gestureRecognizer.view.frame.size.height);
    [gestureRecognizer setTranslation:CGPointZero inView:gestureRecognizer.view.superview];
    
    CGRect sliderFrame = gestureRecognizer.view.frame;
    CGFloat sliderX = sliderFrame.origin.x;
    
    CGFloat maxW = gestureRecognizer.view.superview.frame.size.width - SLIDER_W;
    if (sliderX <= 0) {
        gestureRecognizer.view.frame = CGRectMake(0, sliderFrame.origin.y, sliderFrame.size.width, sliderFrame.size.height);
    }
    
    if (sliderX >= maxW) {
        gestureRecognizer.view.frame = CGRectMake(maxW, sliderFrame.origin.y, sliderFrame.size.width, sliderFrame.size.height);
    }
    
    CGFloat uiPrecise = maxW * self.dataPrecise / (self.dataMax - self.dataMin) ;
    CGFloat currX =  gestureRecognizer.view.frame.origin.x + uiPrecise / 2;
    NSInteger currX_int = [NSString stringWithFormat:@"%.0f",currX * 1000].integerValue;
    int currSection = currX_int / (uiPrecise * 1000);
    
    // 动态改变显示的金额
    NSString *appearString = [NSString stringWithFormat:@"%zd",(self.dataMin + self.dataPrecise * currSection)];
    if ([self.delegate respondsToSelector:@selector(sliderViewDidPanDelegateWithContinuousData:andIndex:andSliderView:)]) {
        [self.delegate sliderViewDidPanDelegateWithContinuousData:appearString andIndex:currSection andSliderView:self];
    }
    
    //
    if (gestureRecognizer.state == 3) {
        gestureRecognizer.view.frame = CGRectMake(currSection * uiPrecise, sliderFrame.origin.y, sliderFrame.size.width, sliderFrame.size.height);
        NSLog(@"\nindex = %zd\nstring = %@\n",currSection,appearString);
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
